package com.zyh.controller;
import com.zyh.entity.User;
import com.zyh.resp.Result;
import com.zyh.service.UserService;
import com.zyh.utils.GetNumber;
import com.zyh.utils.Menu;

import java.util.List;
import java.util.Scanner;
import com.zyh.utils.PermissionUtils;

public class UserController {
    private final UserService userService = new UserService();
    private final Scanner scanner = new Scanner(System.in);
    private final GetNumber getNumber = new GetNumber();
    private final TagController tagController = new TagController();
    private final CommentController commentController = new CommentController();

    public void login() {
        System.out.print("请输入用户名：");
        String username = scanner.nextLine().trim();
        System.out.print("请输入密码：");
        String password = scanner.nextLine().trim();
        try {
            Result<User> result = userService.login(username, password);
            System.out.println(result.getMessage());
            if (result.isSuccess()) {
                manage();
            }
        } catch (Exception e) {
            System.out.println("登录失败：" + e.getMessage());
        }
    }

    public void adduser() {
        if (!PermissionUtils.isAdmin()) {
            System.out.println("操作失败：仅管理员可新增用户");
            return;
        }
        System.out.print("请输入用户名：");
        String username = scanner.nextLine().trim();
        System.out.print("请输入密码：");
        String password = scanner.nextLine().trim();
        System.out.print("请输入邮箱：");
        String email = scanner.nextLine().trim();
        try {
            User user = new User(username, password, email);
            Result<Void> result = userService.add(user);
            System.out.println(result.getMessage());
        } catch (Exception e) {
            System.out.println("添加失败：" + e.getMessage());
        }
    }

    public void register() {
        System.out.print("请输入用户名：");
        String username = scanner.nextLine().trim();
        System.out.print("请输入密码：");
        String password = scanner.nextLine().trim();
        System.out.print("请输入邮箱：");
        String email = scanner.nextLine().trim();
        try {
            User user = new User(username, password, email);
            Result<Void> result = userService.add(user);
            System.out.println(result.getMessage());
        } catch (Exception e) {
            System.out.println("注册失败：" + e.getMessage());
        }
    }

    public void manage() {
        while (true) {
            Menu.userMenu();
            int opt = getNumber.getUserInputAsInt();
            switch (opt) {
                case 1:
                    selectById();
                    break;
                case 2:
                    adduser();
                    break;
                case 3:
                    deleteUser();
                    break;
                case 4:
                    selectByPage();
                    break;
                case 5:
                    selectAll();
                    break;
                case 6:
                    updateById();
                    break;
                case 7:
                    System.out.println("进入标签管理...");
                    tagController.manageFromUser();
                    break;
                case 8:
                    System.out.println("进入评论管理...");
                    commentController.manageFromUser();
                    break;
                case 0:
                    System.out.println("退出登录成功");
                    return;
                default:
                    System.out.println("无效选项，请重新选择");
            }
        }
    }

    private void selectById() {
        System.out.print("请输入用户ID：");
        Integer userId = getNumber.getUserInputAsInt();
        try {
            Result<User> result = userService.selectById(userId);
            User user = result.getData();
            System.out.println("查询结果：ID=" + user.getUserId() + "，用户名=" + user.getUsername() + "，邮箱=" + user.getEmail());
        } catch (Exception e) {
            System.out.println("查询失败：" + e.getMessage());
        }
    }

    private void selectByPage() {
        System.out.print("请输入每页条数：");
        int limit = getNumber.getUserInputAsInt();
        System.out.print("请输入起始偏移量（从0开始）：");
        int offset = getNumber.getUserInputAsInt();
        try {
            Result<List<User>> result = userService.selectByPage(limit, offset);
            System.out.println("分页查询结果（共" + result.getData().size() + "条）：");
            result.getData().forEach(user ->
                    System.out.println("ID=" + user.getUserId() + "，用户名=" + user.getUsername())
            );
        } catch (Exception e) {
            System.out.println("分页查询失败：" + e.getMessage());
        }
    }

    private void selectAll() {
        try {
            Result<List<User>> result = userService.getAll();
            System.out.println("=====所有用户（共" + result.getData().size() + "条）=====");
            result.getData().forEach(user ->
                    System.out.println("ID=" + user.getUserId() + "，用户名=" + user.getUsername() + "，邮箱=" + user.getEmail())
            );
        } catch (Exception e) {
            System.out.println("查询失败：" + e.getMessage());
        }
    }

    public void deleteUser(){
        if (!PermissionUtils.isAdmin()) {
            System.out.println("操作失败：仅管理员可删除用户");
            return;
        }
        System.out.println("请输入要删除用户的id: ");
        Integer userId = scanner.nextInt();
        try {
            Result<Void> result = userService.deleteById(userId);
            System.out.println(result.getMessage());
        } catch (Exception e) {
            System.out.println("删除失败：" + e.getMessage());
        }
    }

    private void updateById() {
        if (!PermissionUtils.isAdmin()) {
            System.out.println("操作失败：仅管理员可修改用户");
            return;
        }
        System.out.print("请输入要修改的用户ID：");
        Integer userId = getNumber.getUserInputAsInt();
        System.out.print("请输入新的邮箱：");
        String newEmail = scanner.nextLine().trim();
        try {
            Result<Void> result = userService.updateById(userId, newEmail);
            System.out.println(result.getMessage());
        } catch (Exception e) {
            System.out.println("修改失败：" + e.getMessage());
        }
    }
}
